package com.meituan.verintreport.task;

import com.meituan.verintreport.db.dao.FlagsOnContactAllMapper;
import com.meituan.verintreport.db.dao.UsersMapper;
import com.meituan.verintreport.db.dto.FlagsOnContactAllDto;
import com.meituan.verintreport.db.dto.UsersDto;
import com.meituan.verintreport.db.verint.VerintBaseTableDao;
import com.meituan.verintreport.util.DateUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "base-table.flags-on-contact-all")
public class BaseTableTaskFlagOnContactAll extends BaseTableTask {
    @Resource
    private FlagsOnContactAllMapper flagsOnContactAllMapper;

    @Resource
    private VerintBaseTableDao verintBaseTableDao;

    @Scheduled(cron = "${base-table.flags-on-contact-all.cron}")
    public void execute() {

        if (!isEnable()){
            return;
        }

        boolean shouldContinue;
        String start = DateUtil.getDate(21, null);
        String end = DateUtil.getDate(2,null);
        log.info("remove start:{},end:{}", start, end);
        Integer rs = flagsOnContactAllMapper.removeByTime(start , end);
        log.info("remove {} data ", rs);

        int pageIndex = 0;
        int pageSize = 1000;

        do {
            shouldContinue = false;
            String start2 = DateUtil.getDate(21, null);
            String end2 = DateUtil.getDate(1,null);
            log.info("got start:{},end:{}", start2, end2);
            List<FlagsOnContactAllDto> records = verintBaseTableDao.
                    getFlagsOnContactAllListByTime(start2, end2,pageIndex, pageSize);
            log.info("got {} records", records.size());
            if (records.size() == 1000) {
                shouldContinue = true;
            }

            for (FlagsOnContactAllDto record : records) {
                try {
                    flagsOnContactAllMapper.insert(record);
                } catch (Exception ex) {
                    log.error("Add GroupsToUser to db exception.", ex);
                }
            }

            pageIndex += pageSize;
        }
        while (shouldContinue);
    }
}
